import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, FormInstance, Popconfirm, Modal, Form, Spin } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { ModalForm } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { 
  getOffHospitalBillList, 
  getOffHospitalSettleList, 
  cancalPay, 
  getDischargeStatus,
  applyOffHospital,
  getOffHospitalDetail,
  getPatientHospitalizationInfo } from '@/services/order/api';
import { isNull, MsgType, showMsg, isSupportSticky } from '@/utils/utils';
import Detail from './Detail'
import Bill from './Bill'
import './style.less'
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import Print from './Print';
import PrintSum from './PrintSum';
import ChoicePatient from '@/components/ChoicePatient';

const Index: React.FC = (props) => {
  const { eventNo } = props.location.query;
  const [patientId, setPatientId] = useState<string>('')
  const [patientInfo, setPatientInfo] = useState<any>({})
  const [loading, setLoading] = useState(false);
  const [curType, setCurType] = useState('');
  const [curSett, setCurSett] = useState(''); // 设置当前结算单号，用于打印
  const [printing, setPrinting] = useState(false); // 是否打印清单
  const [printingSum, setPrintingSum] = useState(false); // 是否打印汇总清单
  
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  const [clickRow1, setClickRow1] = useState(''); // 当前选中的行编号，用于定位颜色
  const { confirm } = Modal;

  const columns: ProColumns<any>[] = [
    {
      title: '病案号',
      dataIndex: 'out_case_no',
      hideInTable: true,
      colSize: 1.1,
      fieldProps: () => {
        return {
          placeholder: '输入完整病案号',
          onPressEnter: (e) => {
            searchInfo();
          }
        }
      }
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      hideInTable: true,
      hideInSearch: !patientId,
      renderFormItem: () => {
        return <Form.Item>
          <span>{patientInfo?.patient_name}</span>
        </Form.Item>
      }
    },
    {
      title: '归属科室',
      dataIndex: 'dept_name',
      hideInTable: true,
      hideInSearch: !patientId,
      colSize: 1.5,
      renderFormItem: () => {
        return <Form.Item>
          <span>{patientInfo?.admission_dept_name || patientInfo?.admission_dept_code}</span>
        </Form.Item>
      }
    },
    {
      title: '床位号',
      dataIndex: 'bed_no',
      hideInTable: true,
      hideInSearch: !patientId,
      renderFormItem: () => {
        return <Form.Item>
          <span>{patientInfo?.bed_no}</span>
        </Form.Item>
      }
    },
    {
      title: '账单类型',
      dataIndex: 'order_type',
      search: false,
      valueType: 'select',
      valueEnum: {
        P: '计划订单',
        O: '一次性订单',
        R: '租赁订单'
      }
    },
    {
      title: '账单编号',
      dataIndex: 'order_id',
      search: false,
      width: 170,
    },
    {
      title: '账单日期',
      dataIndex: 'bill_date',
      search: false
    },
    {
      title: '账单金额',
      valueType: 'money',
      dataIndex: 'bill_price',
      align: 'right',
      search: false
    },
    {
      title: '账单折扣',
      dataIndex: 'discount',
      align: 'right',
      search: false
    },
    {
      title: '结算金额',
      valueType: 'money',
      dataIndex: 'sett_price',
      align: 'right',
      search: false
    },
    {
      title: '结算状态',
      valueType: 'select',
      dataIndex: 'order_status',
      search: false,
      width: 60,
      valueEnum: {
        C: '待结算',
        U: '待结算',
        W: '结算中',
        G: '结算中',
        P: '已结算',
        R: '已退款',
        F: '已结算',
      }
    },
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      align: 'center',
      render: (_, record) => {
        return [
          <PermissionControl key="view" action_id="400404003">
            <a onClick={() => {
              setVisible(true)
              setRecord(record)
              setCurType('bill')
            }}>查看详情</a>
          </PermissionControl>
        ]
      }
    }
  ];
  const columns2: ProColumns<any>[] = [
    {
      title: '结算单号',
      dataIndex: 'manager_order_id',
      search: false
    },
    {
      title: '结算发起时间',
      search: false,
      render: (dom, entity) => {
        return `${entity.create_date} ${entity.create_time}`
      }
    },
    {
      title: '结算金额',
      dataIndex: 'total_price',
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '结算状态',
      dataIndex: 'pay_status',
      valueType: 'select',
      valueEnum: {
        C: '开单',
        E: '作废',
        W: '支付处理中',
        P: '已支付',
        R: '已退款',
        U: '退款处理中',
        F: '已作废'
      },
      search: false
    },
    {
      title: '结算发起人',
      dataIndex: 'create_user_name',
      search: false
    },
    {
      title: '工号',
      dataIndex: 'create_user_id',
      search: false
    },
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      align: 'center',
      render: (_, record) => {
        return [
          <PermissionControl key="view" action_id="400404004">
            <a onClick={() => {
              setVisible(true)
              setRecord(record)
              setCurType('sett')
            }}>查看</a>
          </PermissionControl>,

          (record.pay_status === 'C' || record.pay_status === 'W') && <PermissionControl key="cancel" action_id="400404005">
              <Popconfirm  
                placement="topRight"
                cancelText="再想想" 
                okText="确认取消"
                onConfirm={async () => {
                  try {
                    setLoading(true);
                    await cancalPay(record.manager_order_id)
                    showMsg('已取消', MsgType.SUCCESS)
                    formRef.current?.submit();
                    actionRef2.current?.reload();
                    fetchDischargeStatus({
                      patient_id: patientId,
                      admission_num: patientInfo.visit_no
                    })
                    setLoading(false);
                  } catch (error) {
                    setLoading(false);
                    showMsg(error?.data?.errmsg)
                  }
                }}
                title="取消后当前记录不可恢复，是否继续？">
                <a>取消</a>
              </Popconfirm>
            </PermissionControl>
        ]
      }
    }
  ];
  const actionRef = useRef<ActionType>();
  const actionRef2 = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formRef2 = useRef<FormInstance>();
  const patientRef = useRef(); // 获得患者信息的实例
  const [visible, setVisible] = useState<boolean>(false);
  const [billVisible, setBillVisible] = useState<boolean>(false);
  const [record, setRecord] = useState<any>({})
  // 结算信息查询参数
  const [settleParams, setSettleParams] = useState<any>({});

  const [searchLoading, setSearchLoaing] = useState<boolean>(false);

  const [dischargeStatus, setDischargeStatus] = useState();

  const [printDisable, setPrintDisable] = useState<boolean>(true);

  const [canDischarge, setCanDischarge] = useState<boolean>(true);

  const  handleSettle = async (data: any) => {
    const orderSumbitConfig = {
      title: '',
      content: `订单提交成功，请在【${data?.pay_valid_time}】前完成缴费`,
      cancelText: '知道了',
      okText: '打印结算单',
      onOk() {
        setCurSett(data);
        setPrinting(true);
      },
      onCancel() {
        actionRef.current?.reload();
        actionRef2.current?.reload();
      }
    };
    confirm(orderSumbitConfig);
  }

  const clear = () => {
    setPatientId('')
    setPatientInfo(null);
    actionRef?.current?.reload();
    setSettleParams({
      patient_id: null,
      admission_num: null,
      current: 1,
      pageSize: 1000
    })
    actionRef2.current?.reload();
  }

  // 搜索办结出院信息
  const searchInfo = async (user) => {
    // const out_case_no = formRef.current?.getFieldValue('out_case_no');
    // if (!out_case_no && !out_case_no?.trim()) {
    //   showMsg('请输入病案号');
    //   clear();
    //   return;
    // }

    // if (out_case_no.length < 6 || out_case_no.length > 14) {
    //   showMsg('请输入正确的病案号');
    //   clear();
    //   return
    // }
    // const params = {};
    // if (out_case_no.length > 4 && out_case_no.length < 15 && Number.isFinite(parseFloat(out_case_no))) {
    //   params.out_case_no = out_case_no;
    // } else if (out_case_no.includes('R')) {
    //   params.out_visit_no = out_case_no;
    // }
    // setSearchLoaing(true);
    // const data = await getPatientHospitalizationInfo(params)
    // setSearchLoaing(false);
    // const user = data[0]
    // if (!user) {
    //   showMsg('未找到患者信息', MsgType.INFO);
    //   clear();
    //   return;
    // }

    fetchDischargeStatus({
      patient_id: user.patient_id,
      admission_num: user.visit_no
    })


    setPatientId(user.patient_id)
    setPatientInfo({ ...user, admission_num: user.visit_no })
    actionRef.current?.reload();
    setSettleParams({
      patient_id: user.patient_id,
      admission_num: user.visit_no,
      current: 1,
      pageSize: 1000
    })
    formRef2.current?.submit()
  }

  // 获取出院办结状态
  const fetchDischargeStatus = async (params) => {
    try {
      const data = await getDischargeStatus(params);
      setDischargeStatus(data.manager_status);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    if (!isNull(eventNo)) { // 单点登录来的住院号，则查询用户信息
      // formRef.current?.setFieldsValue({ 'out_case_no': eventNo });
      // searchInfo();
      patientRef.current.fetch?.(eventNo)
    }
  }, []);
  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
       <Spin spinning={loading}>
        <div style={{ background: '#fff', padding: '16px 8px 8px', marginBottom: 4 }}>
          <ChoicePatient
            ref={patientRef}
            label='病案号/住院号'
            placeholder='输入完整病案号/住院号'
            fromTo='discharged'
            showMore={true}
            onChoice={async(info, data) => {
              if (!isNull(info.patient_id)) {
                setPatientInfo(Object.assign({}, info, {admission_num: info.visit_no}));
                searchInfo(info);
                
              } else {
                showMsg('未找到患者信息', MsgType.INFO);
                clear();
              }
            }}
            changePatient={() => {
              clear();
              patientRef?.current?.clear();
            }}
          />
        </div>
        <ProTable<any, { patient_id: string; admission_num: string; } & COMMON.PageParams>
          rowKey="order_id"
          className="custome-table"
          bordered
          formRef={formRef}
          actionRef={actionRef}
          manualRequest={true}
          // cardBordered
          request={async (params) => {
            if (!patientId) {
              setPrintDisable(true);
              setCanDischarge(false);
              return {
                data: [],
                total: 0
              }
            }
            params = Object.assign({}, params, { patient_id: patientId, admission_num: patientInfo.visit_no })
            try {
              const data: any = await getOffHospitalBillList(params);
              setPrintDisable(data.record_list?.length <= 0);
              setCanDischarge(data.record_list?.length > 0);

              return {
                data: data.record_list,
                success: true,
                total: data.sum_record_num
              }
            } catch (error) {
              showMsg(error?.data?.errmsg);
              setPrintDisable(true);
              setCanDischarge(false);
              return {
                data: [],
                success: true,
                total: 0
              }
            }
          }}
          // search={{
          //   className: 'discharge-search-form',
          //   span: 4,
          //   collapsed: false,
          //   collapseRender: () => '',
          //   optionRender: (searchConfig, formProps, dom) => {
          //     return [
          //       <PermissionControl key="search" action_id="400404000">
          //         <Button loading={searchLoading} type="primary" onClick={searchInfo}>查询</Button>
          //       </PermissionControl>
          //     ]
          //   }
          // }}
          search={false}
          options={false}
          headerTitle="账单信息"
          toolBarRender={() => {
            return [
              <PermissionControl key="off" action_id="400404001">
                <Popconfirm 
                  placement="topRight"
                  disabled={dischargeStatus !== 'U' || !canDischarge}
                  key="settle"
                  okText="继续结算"
                  cancelText="再想想"
                  onConfirm={ async () => {
                    try {
                      setLoading(true);
                      await applyOffHospital({
                        patient_id: patientId,
                        admission_num: patientInfo.visit_no
                      })
                      formRef.current?.submit();
                      actionRef2.current?.reload();
                      fetchDischargeStatus({
                        patient_id: patientId,
                        admission_num: patientInfo.visit_no
                      })
                    } catch (error) {
                      setLoading(false);
                      showMsg(error?.data?.errmsg)
                    }
                  }}
                  title={<div>出院办结会停止计划订单的所有项目，<br />并取消所有待结算项目重新发起统一结算，是否继续？</div>}>
                  <Button disabled={dischargeStatus !== 'U'} type="primary">
                    出院办结
                  </Button>
                </Popconfirm>
              </PermissionControl>,
              <PermissionControl key="print" action_id="400404002">
              <Button 
                key="print"
                onClick={() => {
                  setPrintingSum(true);
                }} 
                disabled={!patientId || printDisable || isNull(curSett)}
                type="primary">
                打印汇总单
              </Button>
            </PermissionControl>,
              <PermissionControl key="print" action_id="400404002">
                <Button 
                  key="print"
                  onClick={() => {
                    setPrinting(true);
                  }} 
                  disabled={!patientId || printDisable || isNull(curSett)}
                  type="primary">
                  打印清单
                </Button>
              </PermissionControl>
            ]
          }}
          scroll={{x: 1000}}
          columns={columns}
          pagination={{
            showQuickJumper: true
          }}
          onRow={record => {
            return {
              onClick: event => { setClickRow(record.order_id) }, // 点击行
              onMouseEnter: event => {}, // 鼠标移入行
              onMouseLeave: event => {},
            };
          }}
          rowClassName={(record) => {
            return record.order_id === clickRow ? 'tableRowClick' : ''
          }}
        />

        <ProTable<any, COMMON.PageParams>
          rowKey="manager_order_id"
          className="custome-table settle-table"
          // style={{ margin: '12px' }}
          actionRef={actionRef2}
          bordered
          formRef={formRef2}
          params={settleParams}
          manualRequest={true}
          search={{
            collapsed: false,
            collapseRender: () => '',
            optionRender: () => {
              return []
            }
          }}
          request={async (params) => {
            console.log('actionRef2.params', params);
            if (isNull(params.patient_id)) {
              return {
                data: [],
                success: true,
                total: 0
              }
            }
            try {
              const data: any = await getOffHospitalSettleList(params);
              // 获得正在支付的结算单
              const sett = data.record_list.find(item => item.pay_status === 'W' || item.pay_status === 'P');
              setCurSett(isNull(sett) ? null : sett);
              
              return {
                data: data.record_list,
                success: true,
                total: data.sum_record_num
              }
            } catch (error) {
              showMsg(error?.data?.errmsg);
              return {
                data: [],
                success: true,
                total: 0
              }
            }
          }}
          options={false}
          headerTitle="结算信息"
          scroll={{x: 1000}}
          columns={columns2}
          pagination={false}
          onRow={record => {
            return {
              onClick: event => { setClickRow1(record.manager_order_id) }, // 点击行
              onMouseEnter: event => {}, // 鼠标移入行
              onMouseLeave: event => {},
            };
          }}
          rowClassName={(record) => {
            return record.manager_order_id === clickRow1 ? 'tableRowClick' : ''
          }}
        />
      </Spin>

      {
        visible && <Detail 
          handleModalVisible={setVisible} 
          handleSettle={handleSettle}
          patientInfo={patientInfo}
          record={record}
          type={curType}
          optCallback={() => {
            setBillVisible(true)
          }} />
      }

      {
        billVisible && <Bill 
        handleModalVisible={setBillVisible} 
        patientInfo={patientInfo}
        record={record} 
        optCallback={() => {}} />
      }
      <div style={{ height: 30 }} />
      {printing && <Print detail={curSett} patientInfo={patientInfo} onFinish={() => setPrinting(false)} />}
      {printingSum && <PrintSum detail={curSett} patientInfo={patientInfo} onFinish={() => setPrintingSum(false)} />}
    </PageContainer>
  );
};

export default Index;
